﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ResourceEditor.Core
{
    public class ResourceAssembly
    {
        #region Properties
        private FileInfo File { get; set; }
        private List<ResourceFile> Resources { get; set; }

        public bool HasChanges
        {
            get
            {
                return Resources.Any(item => item.HasChanges);
            }
        }

        public string[] ResoueceNames
        {
            get
            {
                return Resources.Select(item => item.File.Name).ToArray();
            }
        }
        #endregion

        #region Ctor
        public ResourceAssembly(string fileName)
        {
            Resources = new List<ResourceFile>();

            File = new FileInfo(fileName);
            ILHelper.Disassemble(File);

            FileInfo[] files = File.Directory.GetFiles(string.Format("{0}*.resources", File.NameWithoutExtension()));

            List<string> nonLoadItems = new List<string>();
            foreach (FileInfo item in files)
            {
                try
                {
                    Resources.Add(new ResourceFile(item));
                }
                catch (Exception ex)
                {
                    Logger.Exception(ex);
                    nonLoadItems.Add(item.Name);
                }
            }

            if (nonLoadItems.Count > 0)
            {
                throw new Exception(string.Format(Messages.FailedToLoadFiles, nonLoadItems.ToStringAll()));
            }
        }
        #endregion

        #region Indexer
        public ResourceFile this[string name]
        {
            get
            {
                return Resources.Find(item => item.File.Name == name);
            }
        }
        #endregion

        #region Methods
        public void SaveEmbedded()
        {
            foreach (var item in Resources)
            {
                item.SaveEmbedded();
            }

            ILHelper.Reassemble(File);
        }

        public void SaveResx()
        {
            foreach (var item in Resources)
            {
                item.SaveResx();
            }
        }
        #endregion
    }
}
